package com.csdemos.algs;

public class Queue {
	
	private static final int DEFAULT_SIZE = 10;
	
	protected int[] Q;
	protected int head;
	protected int tail;
	
	public Queue() {
		this(DEFAULT_SIZE);
	}
	
	public Queue(int size) {
		Q = new int[size];
		head = 0;
		tail = 0;
	}
	
	public boolean isEmpty() {
		return head == tail;
	}
	
	public boolean isFull() {
		return (head + Q.length - tail) % Q.length == 1;
	}
	
	public void enqueue(int x) {
		if (isFull()) {
			throw new IllegalStateException("Queue is full!");
		}
		Q[tail] = x;
		tail = cycleIncrement(tail);
	}
	
	public int dequeue() {
		if (isEmpty()) {
			throw new IllegalStateException("Queue is empty!");
		}
		int x = Q[head];
		head = cycleIncrement(head);
		return x;
	}
	
	private int cycleIncrement(int index) {
		return (index + 1) % Q.length;
	}
	
	@Override
	public String toString() {
		StringBuilder result = new StringBuilder("[");
		for (int i = 0; i < Q.length; ++i) {
			if (i == head) {
				result.append(" h-> ");
			}
			if (i == tail) {
				result.append(" t-> ");
			}
			result.append(Q[i]).append(" ");
		}
		return result.append("]").toString();
	}

}
